package com.nariano.webapp.util;

import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.IWrapModel;
import org.apache.wicket.model.ResourceModel;

public class ParameterizedResourceModel extends ResourceModel {
	
	private final Object [] objects;
	private String resourceKey;

	public ParameterizedResourceModel(String resourceKey, Object ... objects ) {
		super(resourceKey);
		this.objects = objects;
		this.resourceKey = resourceKey;
	}


	@Override
	public IWrapModel<String> wrapOnAssignment(Component component) {
		return new AssignmentWrapper(resourceKey, component);
	}
	
	/**
	 * 
	 */
	private class AssignmentWrapper extends ResourceModel implements IWrapModel<String>
	{
		private static final long serialVersionUID = 1L;

		private final Component component;

		/**
		 * Construct.
		 * 
		 * @param resourceKey
		 * @param defaultValue
		 * @param component
		 */
		public AssignmentWrapper(String resourceKey, Component component)
		{
			super(resourceKey, "");
			this.component = component;
		}

		/**
		 * @see org.apache.wicket.model.IWrapModel#getWrappedModel()
		 */
		public IModel<String> getWrappedModel()
		{
			return ParameterizedResourceModel.this;
		}

		/**
		 * @see org.apache.wicket.model.AbstractReadOnlyModel#getObject()
		 */
		@Override
		public String getObject()
		{
			String template = Application.get().getResourceSettings().getLocalizer().getString(resourceKey,
				component, "");
			return String.format(template, objects);
		}

		@Override
		public void detach()
		{
			super.detach();
			ParameterizedResourceModel.this.detach();
		}

	}

}
